﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using UnityEngine;
public interface IPackageInfo
{

}

public class PackageInfo :IPackageInfo
{
    public DataEventArgs Data;
    public PackageInfo(DataEventArgs data)
    {
        this.Data = data;
    }
}
class NetClient  
{
    ClientSession m_Session;
    private Action<IPackageInfo> m_Handler;
    private bool m_Connected = false;
    public event EventHandler Connected;
    public NetClient(Action<IPackageInfo> handlerFunc)
    {
        this.m_Handler = handlerFunc;
    }

    public void ConnectAsync(EndPoint remoteEndPoint)
    {
        this.m_Session = new ClientSession();
        this.m_Session.DataReceived += OnSessionDataReceived;
        this.m_Session.Connected += OnSessionConnected;
        this.m_Session.Connect(remoteEndPoint);
    }

    private void OnSessionConnected(object sender, EventArgs e)
    {
        m_Connected = true;
        if (this.Connected != null)
        {
            this.Connected(this,EventArgs.Empty);
        }
    }

    public void Send(byte[] data)
    {
        if (m_Session != null)
        {
            m_Session.Send(new ArraySegment<byte>(data, 0, data.Length));
        }
        else
        {
            Debug.LogError("Session为空不能发送消息");
        }
    }

   
    void OnSessionDataReceived(object sender, DataEventArgs e)
    {
        if (m_Handler != null)
        {
            m_Handler(new PackageInfo(e));
        }
    }
    public void Close()
    {
        if (this.m_Session != null)
        {
            this.m_Session.Close();
        }
    }
}

